﻿using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Reflection;

namespace LiJ.Common.Extention.Volidate
{
    /// <summary>
    /// 类型帮助类
    /// </summary>
    public static class TypeHelper
    {
        /// <summary>
        /// 线程安全属性字典
        /// </summary>
        private static ConcurrentDictionary<string, object[]> attributeDictionaries = new ConcurrentDictionary<string, object[]>();

        /// <summary>
        /// 线程安全属性特性集合字典
        /// </summary>
        private static ConcurrentDictionary<string, PropertyInfo[]> propertyDictionaries = new ConcurrentDictionary<string, PropertyInfo[]>();

        /// <summary>
        /// 获取属性的属性
        /// </summary>
        /// <param name="typeName">类型名称</param>
        /// <param name="propertyInfo">字段属性信息</param>
        /// <param name="attributeType">字段属性的属性类型</param>
        /// <returns>对象数组</returns>
        public static object[] GetPropertiAttributes(string typeName, PropertyInfo propertyInfo, Type attributeType)
        {
            var key = typeName + propertyInfo.Name;
            attributeDictionaries.TryGetValue(key, out var array);
            if (array != null)
            {
                return array;
            }

            array = propertyInfo.GetCustomAttributes(attributeType, true).ToArray();
            attributeDictionaries.TryAdd(key, array);
            return array;
        }

        /// <summary>
        /// 获取属性集合
        /// </summary>
        /// <param name="type">类型</param>
        /// <returns>属性集合</returns>
        public static PropertyInfo[] GetProperties(Type type)
        {
            propertyDictionaries.TryGetValue(type.FullName, out var properties);
            if (properties != null)
            {
                return properties;
            }

            properties = type.GetProperties();
            propertyDictionaries.TryAdd(type.FullName, properties);
            return properties;
        }
    }
}